<template>
	<view class="login">
		<view v-if="canIUse">
			<web-view v-if="judge" :src="url" @message="handlemessage" onPostMessage="onPostMessage">
			</web-view>
			<view v-else>
				<view class='header'>
					<image src='/static/logo.png'></image>
				</view>
				<view class='content'>
					<view>申请获取以下权限</view>
					<text>获得你的公开信息(昵称，头像等)</text>
				</view>
				<button class='bottom' type='primary' open-type="getUserInfo" @getuserinfo="getuserinfo" lang="zh_CN"
					@bindgetuserinfo="bindGetUserInfo">
					确认授权
				</button>
			</view>
		</view>
		<view class="" v-else>
			请升级微信版本
		</view>
	</view>
</template>

<script>
	import {
		decodeToken
	} from '@/utils/jsrsasign.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				url: 'http://192.144.217.175',
				judge: false,
				canIUse: wx.canIUse('button.open-type.getUserInfo'),
				user: ''
			};
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken']),
			// 用户授权后获取用户基本信息
			getuserinfo(e) {
				// console.log(e.detail);
				this.user = e.detail.userInfo
				this.getToken(e.detail)
			},
			async handlemessage(event) {
				console.log(event.detail.data[0])
				let {
					data: res
				} = await uni.$http.get('/login/getToken', {
					code: event.detail.data[0].code,
					state: event.detail.data[0].state
				})
				if (res.code !== 200) return uni.$showMsg('登录失败！')
				this.user.userId = decodeToken(res.date).userId
				this.updateToken(res.date)
				this.updateUserInfo(this.user)
				// console.log(decodeToken(res.date));
				// console.log(this.userInfo);
				// uni.navigateBack({
				// 	delta: 1
				// })
				// if (evt.detail.data[0].action == 'back') {}
				// if (event.detail.data[0].action == 'success') {
				// 	uni.reLaunch({
				// 		url: '/pages/index/index'
				// 	})
				// }
			},
			async getToken(info) {
				// 获取 code 对应的值
				const [err, res] = await uni.login().catch(err => err)

				// if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
				uni.$http.baseUrl = 'https://api.weixin.qq.com'
				const {
					data: loginResult
				} = await uni.$http.get("/sns/jscode2session", {
					js_code: res.code,
					grant_type: 'authorization_code',
					// encryptedData: info.encryptedData,
					// iv: info.iv,
					// rawData: info.rawData,
					// signature: info.signature,
					appid: 'wxdb4e573cb92c95cf',
					secret: '8723fa695a5bdeb62cca6361e5e46f1f'
				})
				uni.$http.baseUrl = 'http://101.43.254.109:8081'
				// console.log(loginResult);
				this.judge = true
				// if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')

				// 直接把 token 保存到 vuex 中
				// this.updateToken(loginResult.message.token)
				// this.navigateBack()
			},
			bindGetUserInfo: function(e) {
				// console.warn(e);
				if (e.detail.userInfo) {
					//用户按了允许授权按钮
					var that = this;
					// 获取到用户的信息了，打印到控制台上看下
					// console.log("用户的信息如下：");
					// console.log(e.detail.userInfo);
					//授权成功后,跳转页面
					wx.switchTab({
						url: '/pages/home/home', //这里填入要跳转目的页面的url
						success: (result) => {
							console.log("跳转到首页");
						},
						fail: () => {}
					});
				} else {
					//用户按了拒绝按钮
					wx.showModal({
						title: '警告',
						content: '您拒绝了授权，将无法进入小程序，请授权之后再进入!',
						showCancel: false,
						confirmText: '返回',
						success: function(res) {
							// 用户没有授权成功，不需要改变 isHide 的值
							if (res.confirm) {
								console.log('用户点击了“返回”');
							}
						}
					});
				}
			},
		},
		async onLoad(e) {
			// 测试避免多次登录
			uni.redirectTo({
				url: '/pages/index/index'
			});

			let {
				data: res
			} = await uni.$http.get('/login/getLoginUrl')
			res.code === 200 ? this.url = res.date : ''
			if (!this.token) {
				uni.$showMsg('请先登录')
			} else {

			}
			wx.authorize()
			var that = this;
			// 查看是否授权
			wx.getSetting({
				success: function(res) {
					if (res.authSetting['scope.userInfo']) {
						wx.getUserInfo({
							success: function(res) {
								// 用户已经授权过,调用微信的 wx.login 接口，从而获取code,再直接跳转到主页
								wx.login({
									success: res => {
										// 获取到用户的 code 之后：res.code
										// console.log("用户的code:" + res.code);
									}
								});
								wx.switchTab({
									url: '/pages/home/home', //这里填入要跳转目的页面的url
									success: (result) => {
										console.log("跳转到首页");
									},
									fail: () => {}
								});
							}
						});
					} else {
						// 用户没有授权，显示授权页面,这里不进行操作
					}
				}
			});
		},
		computed: {
			...mapState('m_user', ['token', 'userInfo'])
		}
	}
</script>

<style lang="scss">
	.login {
		text-align: center;
	}

	.header {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
	}

	.header image {
		width: 200rpx;
		height: 200rpx;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 70rpx 50rpx;
		font-size: 35rpx;
	}
</style>
